using Microsoft.EntityFrameworkCore;
using Terra.Core.Common.Models.Pagination;
using Terra.Data.Context;
using Terra.Data.Entities.Logging;

namespace Terra.Data.Repository.Logging;

/// <summary>
/// 登录日志仓储实现
/// </summary>
public class LoginLogRepository : RepositoryBase<LoginLog, Guid>, ILoginLogRepository
{
    private readonly TerraDbContext _context;

    public LoginLogRepository(TerraDbContext dbContext) : base(dbContext)
    {
        _context = dbContext;
    }


    /// <inheritdoc />
    public async Task<PagedList<LoginLog>> GetPagedListAsync(
        string userName = null,
        bool? status = null,
        DateTime? startTime = null,
        DateTime? endTime = null,
        int pageIndex = 1,
        int pageSize = 10)
    {
        var query = GetQueryable();

        // 应用过滤条件
        if (!string.IsNullOrWhiteSpace(userName))
        {
            query = query.Where(x => x.UserName.Contains(userName));
        }

        if (status.HasValue)
        {
            query = query.Where(x => x.Status == status.Value);
        }

        if (startTime.HasValue)
        {
            query = query.Where(x => x.LoginTime >= startTime.Value);
        }

        if (endTime.HasValue)
        {
            query = query.Where(x => x.LoginTime <= endTime.Value);
        }

        // 获取总记录数
        var totalCount = await query.CountAsync();

        // 分页查询
        query =  query
            .OrderByDescending(x => x.LoginTime);

        return PagedList<LoginLog>.Create(query, pageIndex, pageSize);
    }



    /// <inheritdoc />
    public async Task<int> CleanAsync(DateTime beforeTime)
    {
        var logs = await GetListAsync(x => x.LoginTime < beforeTime);
        if (!logs.Any())
        {
            return 0;
        }

        await DeleteRangeAsync(logs);
        return logs.Count;
    }
}